<template>
  <div class="project-list">
    <h1>项目列表</h1>
    
    <div class="search-bar">
      <el-input v-model="searchOwner" placeholder="组织名称" clearable @input="handleSearch" />
      <el-input v-model="searchName" placeholder="库名称" clearable @input="handleSearch" />
      <el-button type="primary" @click="handleSearch">
        <el-icon><Search /></el-icon>
      </el-button>
      <el-button @click="resetSearch">重置</el-button>
      <el-button type="primary" @click="showAddDialog">添加项目</el-button>
      <el-button type="danger" :disabled="!selectedProjects.length" @click="batchDelete">
        批量删除
      </el-button>
    </div>
    
    <el-table 
      :data="paginatedData" 
      v-loading="loading"
      @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" />
      <el-table-column prop="displayId" label="序号" width="80" />
      <el-table-column prop="owner" label="组织名称" width="150" />
      <el-table-column prop="name" label="库名称" width="150" />
      <el-table-column prop="description" label="描述" />
      <el-table-column prop="gitUrl" label="GitCode地址" width="500" />
      <el-table-column label="操作" width="200">
        <template #default="scope">
          <el-button size="small" @click="showEditDialog(scope.row)">编辑</el-button>
          <el-button size="small" type="danger" @click="deleteProject(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination-container">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50]"
        :total="projects.length"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
    
    <!-- 添加/编辑项目对话框 -->
    <el-dialog v-model="dialogVisible" :title="isEdit ? '编辑项目' : '添加项目'">
      <el-form :model="form" label-width="120px">
        <el-form-item 
          label="组织名称" 
          prop="owner"
          :rules="[
            { required: true, message: '请选择组织名称', trigger: 'change' }
          ]">
          <el-select v-model="form.owner" placeholder="请选择组织名称">
            <el-option label="openharmony-sig" value="openharmony-sig" />
            <el-option label="openharmony-tpc" value="openharmony-tpc" />
            <el-option label="openharmony_tpc_samples" value="openharmony_tpc_samples" />
          </el-select>
        </el-form-item>
        <el-form-item 
          label="库名称" 
          prop="name"
          :rules="[
            { required: true, message: '请输入库名称', trigger: 'blur' }
          ]">
          <el-input v-model="form.name" />
        </el-form-item>
        <el-form-item label="描述">
          <el-input v-model="form.description" type="textarea" />
        </el-form-item>
        <el-form-item label="Git地址">
          <el-input v-model="form.gitUrl" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveProject">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Refresh } from '@element-plus/icons-vue'
import { projectApi } from '../api'

export default {
  name: 'ProjectList',
  components: {
    Search,
    Refresh
  },
  setup() {
    // 添加分页相关的变量
    const currentPage = ref(1)
    const pageSize = ref(10)
    const selectedProjects = ref([])
    const projects = ref([])
    const loading = ref(false)
    const searchOwner = ref('')
    const searchName = ref('')
    const dialogVisible = ref(false)
    const isEdit = ref(false)
    const form = ref({
      id: null,
      owner: '',
      name: '',
      description: '',
      gitUrl: ''
    })

    const loadProjects = async () => {
      loading.value = true
      try {
        const response = await projectApi.getAll()
        projects.value = response.data
      } catch (error) {
        console.error('加载项目失败:', error)
        ElMessage.error('加载项目失败')
      } finally {
        loading.value = false
      }
    }

    // 添加刷新项目信息方法
    const refreshProjects = async () => {
      try {
        await ElMessageBox.confirm('确定要刷新所有项目信息吗？这可能需要一些时间。', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'info'
        })
        
        loading.value = true
        await projectApi.refresh()
        ElMessage.success('项目信息刷新成功')
        await loadProjects()
      } catch (error) {
        if (error !== 'cancel') {
          console.error('刷新项目信息失败:', error)
          ElMessage.error('刷新项目信息失败')
        }
      } finally {
        loading.value = false
      }
    }

    const handleSearch = async () => {
      loading.value = true
      try {
        let response
        if (searchOwner.value && !searchName.value) {
          response = await projectApi.getByOwner(searchOwner.value)
        } else if (!searchOwner.value && searchName.value) {
          response = await projectApi.getByName(searchName.value)
        } else if (searchOwner.value && searchName.value) {
          response = await projectApi.getByOwnerAndName(searchOwner.value, searchName.value)
        } else {
          response = await projectApi.getAll()
        }
        projects.value = response.data
      } catch (error) {
        console.error('搜索项目失败:', error)
        ElMessage.error('搜索项目失败')
      } finally {
        loading.value = false
      }
    }
    
    // 修改 searchProjects 方法
    const searchProjects = async () => {
      loading.value = true
      try {
        const response = await projectApi.search(searchKeyword.value)
        projects.value = response.data
      } catch (error) {
        console.error('搜索项目失败:', error)
        ElMessage.error('搜索项目失败')
      } finally {
        loading.value = false
      }
    }

    const showAddDialog = () => {
      isEdit.value = false
      form.value = {
        id: null,
        owner: '',
        name: '',
        description: '',
        gitUrl: ''
      }
      dialogVisible.value = true
    }

    const showEditDialog = (project) => {
      isEdit.value = true
      form.value = { ...project }
      dialogVisible.value = true
    }

    const saveProject = async () => {
      try {
        if (isEdit.value) {
          await projectApi.update(form.value.id, form.value)
          ElMessage.success('项目更新成功')
        } else {
          await projectApi.create(form.value)
          ElMessage.success('项目添加成功')
        }
        dialogVisible.value = false
        loadProjects()
      } catch (error) {
        console.error('保存项目失败:', error)
        ElMessage.error('保存项目失败')
      }
    }

    const deleteProject = async (id) => {
      try {
        await ElMessageBox.confirm('确定要删除这个项目吗？', '警告', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        
        await projectApi.delete(id)
        ElMessage.success('项目删除成功')
        loadProjects()
      } catch (error) {
        if (error !== 'cancel') {
          console.error('删除项目失败:', error)
          ElMessage.error('删除项目失败')
        }
      }
    }

    onMounted(() => {
      loadProjects()
    })

    const resetSearch = () => {
      searchOwner.value = ''
      searchName.value = ''
      loadProjects()
    }

    // 添加分页计算属性
    const paginatedData = computed(() => {
      const start = (currentPage.value - 1) * pageSize.value
      const end = start + pageSize.value
      return projects.value.slice(start, end)
    })

    // 添加多选框相关方法
    const handleSelectionChange = (val) => {
      selectedProjects.value = val
    }

    const batchDelete = async () => {
      try {
        await ElMessageBox.confirm(
          `确定要删除选中的 ${selectedProjects.value.length} 个项目吗？`, 
          '警告', 
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        )
        
        // 修改这里，收集所有选中项目的ID并一次性发送
        const ids = selectedProjects.value.map(project => project.id)
        await projectApi.batchDelete(ids)
        
        ElMessage.success('批量删除成功')
        loadProjects()
      } catch (error) {
        if (error !== 'cancel') {
          console.error('批量删除失败:', error)
          ElMessage.error('批量删除失败')
        }
      }
    }

    const handleSizeChange = (val) => {
      pageSize.value = val
      currentPage.value = 1
    }

    const handleCurrentChange = (val) => {
      currentPage.value = val
    }

    // 在 return 中添加新的属性和方法
    return {
      projects,
      loading,
      searchOwner,
      searchName,
      dialogVisible,
      isEdit,
      form,
      currentPage,
      pageSize,
      paginatedData,
      selectedProjects,
      handleSearch,
      loadProjects,
      searchProjects,
      showAddDialog,
      showEditDialog,
      saveProject,
      deleteProject,
      resetSearch,
      handleSelectionChange,
      batchDelete,
      handleSizeChange,
      handleCurrentChange,
    }
  }
}
</script>

<style scoped>
.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
  margin-bottom: 60px;
}

.project-list {
  padding: 20px;
}

.search-bar {
  display: flex;
  margin-bottom: 20px;
  gap: 10px;
}

.search-bar .el-input {
  max-width: 200px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
}
</style>